<?php namespace App\Core\Service;

trait Listenable{
    
    protected $listeners = [];
    
    public function getListeners(){
        return $this->listeners;
    }
    
    public function addListeners(Array $listeners){
        foreach($listeners as $name => $listener){
            $this->addListener($listener, !is_numeric($name) ? $name : '');
        }
        return $this;
    }
    
    public function addListener(Listener $listener, $name = ''){
        $listener->boot($this);
        if($name){
            $listener->setName($name);
        }
        $this->listeners[$listener->getName()] = $listener;
        return $this;
    }
    
    public function removeListener($name){
        if(isset($this->listeners[$name])){
            unset($this->listeners[$name]);
        }
        return $this;
    }
    
    public function fireEvent($name){
        if(!$name){
            throw new \Exception('parameter not validated');
        }
        $args = func_get_args();
        foreach($this->getListeners() as $listener){
            call_user_func_array([$listener, 'fire'], $args);
        }
        return $this;
    }
}
